package com.ruc.dbiir.rest.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruc.dbiir.rest.utils.Config;
import com.ruc.dbiir.rest.utils.ParseUtil;
import com.ruc.dbiir.rest.utils.ReadFileUtil;
import com.ruc.dbiir.rest.utils.SSHWindows;


@Controller
@RequestMapping(value = "/highEchart")
public class HignChartsController {




	/**
	 * 获取节点文件
	 * author：mark   
	 * createTime：Sep 7, 2018 4:54:46 PM
	 * @return
	 */
	@RequestMapping(value = "/getGraphNode")
	@ResponseBody
	public Object getGraphNode(@RequestParam(value = "graphName") String graphName) {

		System.out.println("getGraphNode:"+graphName);
		String filePath = Config.RESULT_PATH+graphName+"/g1_new_nodes_as_files_item.csv";
		//		String filePath = "/Users/mark/Documents/MasterLife/GraphDB/neo4j-community-3.4.6/import/Wechatbom_item.csv";
		List<String> list  = ReadFileUtil.readTxtFileIntoStringArrList(filePath);
		//		System.out.println(list.toString());
		return list;
	}

//	
	
	
	
	
	/**
	 * 获取边数据
	 * author：mark   
	 * createTime：Sep 7, 2018 4:54:58 PM
	 * @return
	 */
	@RequestMapping(value = "/getGraphEdge")
	@ResponseBody
	public Object getGraphEdge(@RequestParam(value = "graphName") String graphName) {
		String filePath = Config.RESULT_PATH+graphName+"/g1_new_nodes_as_files_relation.csv";
		//		String filePath = "/Users/mark/Documents/MasterLife/GraphDB/neo4j-community-3.4.6/import/Wechatbom_relation.csv";
		List<String> list  = ReadFileUtil.readTxtFileIntoStringArrList(filePath);
		//		System.out.println(list.toString());
		return list;
	}



	//	@RequestMapping(value = "/startGens")
	//	@ResponseBody
	//	public Object genConf( @RequestParam(value = "username") String username,  @RequestParam(value = "passwd") String passwd,
	//			@RequestParam(value = "nodetype") String nodetype,@RequestParam(value = "edgetype") String edgetype,
	//			@RequestParam(value = "querysize") String querysize,@RequestParam(value = "graphsize") String graphsize) {
	//		System.out.println("genConf Parameters:"+username+passwd+nodetype+edgetype+querysize+graphsize);
	//		
	////		try {
	////			graphsize = URLEncoder.encode(graphsize, "UTF-8");
	////			System.out.println(graphsize);
	////		} catch (UnsupportedEncodingException e1) {
	////			e1.printStackTrace();
	////		}
	//		
	//		String url = Config.GRAPH_ADDR+"/startGen?"+username+"&"+passwd
	//				+"&"+nodetype+"&"+edgetype+"&"+querysize+"&"+graphsize;
	//		System.out.println("url:"+url);
	//		String resultStr = "";
	//		try {
	//			ClientHttpRequest request  = new SimpleClientHttpRequestFactory().createRequest(new URI(url), HttpMethod.GET);
	//			ClientHttpResponse response = request.execute();
	//			
	//			if (response.getStatusCode()==HttpStatus.OK) {
	//				System.out.println("return ok");
	//			}
	//			InputStream is = response.getBody();
	//			byte bytes[] = new byte[(int)response.getBody().available()];
	//			is.read(bytes);
	//			resultStr = new String(bytes, Charset.forName("utf-8"));
	//			System.out.println(resultStr);
	//		} catch (IOException e) {
	//			resultStr = e.getMessage();
	//			e.printStackTrace();
	//		} catch (URISyntaxException e) {
	//			resultStr = e.getMessage();
	//			e.printStackTrace();
	//		}
	//
	//		return ParseUtil.toObject(resultStr);
	//	}


	/**
	 * 向生成器发送请求进行数据生成
	 * author：mark   
	 * createTime：Sep 7, 2018 4:55:58 PM
	 * @param username
	 * @param passwd
	 * @param nodetype
	 * @param edgetype
	 * @param querysize
	 * @param graphsize
	 * @return
	 */

	//	username:data.field.username, passwd:data.field.passwd, 
	//	nodetype:data.field.nodetype,edgetype:data.field.edgetype,
	//	querysize:data.field.querySize,graphsize:data.field.graphSize,
	//	graphLayer:data.field.graphLayer,graphNum:data.field.graphNum

	@RequestMapping(value = "/startGenData")
	@ResponseBody
	public Object urlcon( @RequestParam(value = "username") String username,  @RequestParam(value = "passwd") String passwd,
			@RequestParam(value = "nodetype") String nodetype,@RequestParam(value = "edgetype") String edgetype,
			@RequestParam(value = "querySize") String querySize,@RequestParam(value = "graphSize") String graphSize,
			@RequestParam(value = "graphLayer") String graphLayer,@RequestParam(value = "graphNum") String graphNum,
			@RequestParam(value = "dtype") String dtype) {

		HttpURLConnection urlCon = null;
		StringBuilder result = null;
		try {
			String urls = Config.PYSERVER_ADDR+"/startGenData?"+username+"&"+passwd
					+"&"+nodetype+"&"+edgetype+"&"+querySize+"&"+graphSize+"&"+graphLayer+"&"+graphNum+"&"+dtype;
			System.out.println(urls);
			URL url = new URL(urls);
			urlCon = (HttpURLConnection)url.openConnection();
			urlCon.setConnectTimeout(300 * 1000);
			urlCon.setReadTimeout(300 * 1000);
			urlCon.setRequestMethod("GET");
			InputStream is =  urlCon.getInputStream();
			InputStreamReader isr = new InputStreamReader(is);
			BufferedReader br = new BufferedReader(isr);
			String inputLine=null;
			result = new StringBuilder("");
			if((inputLine = br.readLine()) != null){
				System.out.println(inputLine);
				result.append(inputLine+"<br>");
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (ProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println(result);
		urlCon.disconnect();
		return ParseUtil.toObject(result.toString());
	}

	/**
	 * 向生成器发送请求进行数据生成
	 * author：mark   
	 * createTime：Sep 7, 2018 4:55:58 PM
	 * @param username
	 * @param passwd
	 * @param nodetype
	 * @param edgetype
	 * @param querysize
	 * @param graphsize
	 * @return
	 */

	//	username:data.field.username, passwd:data.field.passwd, 
	//	nodetype:data.field.nodetype,edgetype:data.field.edgetype,
	//	querysize:data.field.querySize,graphsize:data.field.graphSize,
	//	graphLayer:data.field.graphLayer,graphNum:data.field.graphNum

	@RequestMapping(value = "/startGenQuery")
	@ResponseBody
	public Object urlcon( @RequestParam(value = "type") String type) {

		HttpURLConnection urlCon = null;
		StringBuilder result = null;
		try {
			String urls = Config.PYSERVER_ADDR+"/startGenQuery?"+type;
			System.out.println(urls);
			URL url = new URL(urls);
			urlCon = (HttpURLConnection)url.openConnection();
			urlCon.setConnectTimeout(300 * 1000);
			urlCon.setReadTimeout(300 * 1000);
			urlCon.setRequestMethod("GET");
			InputStream is =  urlCon.getInputStream();
			InputStreamReader isr = new InputStreamReader(is);
			BufferedReader br = new BufferedReader(isr);
			String inputLine=null;
			result = new StringBuilder("");
			if((inputLine = br.readLine()) != null){
				System.out.println(inputLine);
				result.append(inputLine+"<br>");
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (ProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println(result);
		urlCon.disconnect();
		return ParseUtil.toObject(result.toString());
	}
	
	
	
	/**
	 * 从数据仓库（数据库）获取预警流水
	 * author：mark   
	 * createTime：Dec 9, 2019 12:01:34 AM
	 * @return
	 */
	@RequestMapping(value = "/getWarnWater")
	@ResponseBody
	public Object getWarnWater()
	{
//		System.out.println("getwaarn==============");
		Random random = new Random();
		int node_disk_rate = random.nextInt(100);
		int node_mem_rate = random.nextInt(100);
		int node_cpu_rate = random.nextInt(50);
		int aa = random.nextInt(50);
		int bb = random.nextInt(50);

		String msg = node_cpu_rate+","+node_disk_rate+","+node_mem_rate+","+aa+","+bb;

		return ParseUtil.toObject(msg);
		
	}
	

	/**
	 * 获取内容列表
	 * author：mark   
	 * createTime：Sep 7, 2018 4:56:20 PM
	 * @return
	 */
	@RequestMapping(value = "/getContentList")
	@ResponseBody
	public Object getContentList() {
//		System.out.println("jjjjjjjjjj");
		String command = "sh " + Config.CMD_ADDR_LIST;
		final List<String> processList = new ArrayList<String>(); 

		try {  
			final Process process = Runtime.getRuntime().exec(command);  	
			BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));  
			String line = "";  
			while ((line = input.readLine()) != null) {  
				line = line+"/suf";System.out.println(line);
				processList.add(line.split("/")[0]+"&"+line.split("/")[1]); 
			}  
			input.close(); 
		} catch (IOException e) {  
			e.printStackTrace();  
		}  
		for (String line : processList) {  
			System.out.println(line);  
		}  
		return processList;
		//		return ParseUtil.toObject("sss");
	}


	/**
	 * 自动化进行测试
	 * author：mark   
	 * createTime：Sep 7, 2018 4:56:20 PM
	 * @return
	 */
	@RequestMapping(value = "/testPerformance")
	@ResponseBody
	public Object testPerformance(@RequestParam(value = "graphName") String graphName,@RequestParam(value = "dbPath") String dbPath) {

	    System.out.println(graphName+"dddd"+dbPath);
		//		String shpath="/Users/mark/program/proWorkspace/pyCharmSrc/GenGraph/result/Execute_Command.sh";//.sh文件的绝对路径
		String command = "sh " + Config.RESULT_PATH+graphName+"/Execute_Command.sh "+dbPath;

		final List<String> processList = new ArrayList<String>(); 
		try {  

			final Process process = Runtime.getRuntime().exec(command);  	
			BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));  
			String line = "";  
			while ((line = input.readLine()) != null) {  
				processList.add(line); 
			}  
			input.close(); 

		} catch (IOException e) {  
			e.printStackTrace();  
		}  
		for (String line : processList) {  
			System.out.println(line);  
		}  
		return processList;
		//		return ParseUtil.toObject("sss");
	}
	
	
	/**
	 * 自动化进行测试
	 * author：mark   
	 * createTime：Sep 7, 2018 4:56:20 PM
	 * @return
	 */
	@RequestMapping(value = "/loadData")
	@ResponseBody
	public Object loadData(@RequestParam(value = "dsName") String dsName) {

	    System.out.println(dsName);
//		String shpath="/Users/mark/program/proWorkspace/pyCharmSrc/GenGraph/result/Execute_Command.sh";//.sh文件的绝对路径
		String command = "sh " + Config.CMD_LOAD ;

		final List<String> processList = new ArrayList<String>(); 
		try {  

			final Process process = Runtime.getRuntime().exec(command);  	
			BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));  
			String line = "";  
			while ((line = input.readLine()) != null) {  
				processList.add(line); 
			}  
			input.close(); 

		} catch (IOException e) {  
			e.printStackTrace();  
		}  
		for (String line : processList) {  
			System.out.println(line);  
		}  
		return processList;
		//		return ParseUtil.toObject("sss");
	}
	
	
	/**
	 * 自动化进行测试Oracle
	 * author：mark   
	 * createTime：Sep 7, 2018 4:56:20 PM
	 * @return
	 */
	@RequestMapping(value = "/testPerformanceOracle")
	@ResponseBody
	public static Object testPerformanceOracle() {

//		2019-10-21 16:29:21.356000
//		2019-10-21 16:29:21.361000
//		2019-10-21 16:29:21.387000
//		2019-10-21 16:29:21.410000
//		2019-10-21 16:29:21.480000
		List<String> timelist = SSHWindows.executeWinCmd();
		List<Integer> tarr = new ArrayList<>();
		List<Integer> tre = new ArrayList<>();
		
		for(int i=0;i<timelist.size();i++) {
			String timestr = timelist.get(i);
			String arr[] = timestr.split(":");
			System.out.println(arr[0]+"|"+arr[1]+"|"+arr[2]);
			int min = Integer.parseInt(arr[1]);
			String ssString = arr[2].replace('.', '-');
			String ss[] = ssString.split("-");
//			System.out.println(ss[0]+"--"+ss[1]);
			int sec = Integer.parseInt(ss[0]);
			int millsec = Integer.parseInt(ss[1]);
//			
			int ts = min*60*1000+sec*1000+millsec/1000;
			tarr.add(ts);
		}
//		
		for (int i = 0; i < tarr.size()-1; i++) {
			tre.add(tarr.get(i+1)-tarr.get(i));
			System.out.println(tre.get(i));
		}
		
		return tre;
	}
	
	
	/**
	 * 添加数据库
	 * author：mark   
	 * createTime：Sep 7, 2018 4:56:20 PM
	 * @return
	 */
	@RequestMapping(value = "/addDatabase")
	@ResponseBody
	public Object addDatabase(@RequestParam(value = "dbName") String dbName,@RequestParam(value = "dbType") String dbType,
			@RequestParam(value = "dbPath") String dbPath) {
		//		System.out.println("adddddddddd----------dbdb");
		String path = Config.RESULT_PATH+"dbCollect.csv";
		String content = dbName+","+dbType+","+dbPath+"\n";
		boolean append = true;
		ReadFileUtil.directFileWriter(path, content, append);
		return ParseUtil.toObject("success");
	}

	/**
	 * 获取数据库
	 * author：mark   
	 * createTime：Sep 7, 2018 4:56:20 PM
	 * @return
	 */
	@RequestMapping(value = "/getDatabase")
	@ResponseBody
	public Object getDatabase() {
		String path = Config.RESULT_PATH+"dbCollect.csv";
		List<String> dbList = ReadFileUtil.readFile(path);
		for (int i = 0; i < dbList.size(); i++) {
			System.out.println(dbList.get(i));
		}
		return dbList;
	}

	
	/**
	 * 获取查询负载
	 * author：mark   
	 * createTime：Sep 7, 2018 4:56:20 PM
	 * @return
	 */
	@RequestMapping(value = "/getWorkload")
	@ResponseBody
	public Object getWorkload() {
		String command = "sh " + Config.CMD_WORKLOAD_LIST;
		final List<String> processList = new ArrayList<String>(); 

		try {  
			final Process process = Runtime.getRuntime().exec(command);  	
			BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));  
			String line = "";  
			while ((line = input.readLine()) != null) {  
				line = line+"/suf";System.out.println(line);
				processList.add(line.split("/")[0]+"&"+line.split("/")[1]); 
			}  
			input.close(); 
		} catch (IOException e) {  
			e.printStackTrace();  
		}  
		for (String line : processList) {  
			System.out.println(line);  
		}  
		return processList;
	}


	/**
	 * 获取一个可用的数据库用以倒入数据并展示
	 * author：mark   
	 * createTime：Oct 14, 2019 6:59:32 PM
	 * @return
	 */
	public String getAvaliableDBPath() {
//		String path = Config.RESULT_PATH+"dbCollect.csv";
//		List<String> dbList = ReadFileUtil.readFile(path);
//		String dbStr = dbList.get(0);
//		String arr[] = dbStr.split(",");
//		String dbPath = arr[2];
		return "/home/ubuntu/graph/neo4j-community-3.4.6";
	}

	@RequestMapping(value = "/getDatabaseList")
	@ResponseBody
	public Object getDatabaseList() {
		String path = Config.RESULT_PATH+"dbCollect.csv";
		JSONArray  jsonArray = new JSONArray();
		JSONObject jObj = new JSONObject();
		List<String> dbList = ReadFileUtil.readFile(path);
		for (int i = 0; i < dbList.size(); i++) {
			System.out.println(dbList.get(i));
			String dbStr = dbList.get(i);
			String arr[] = dbStr.split(",");
			JSONObject jObject = new JSONObject();
			System.out.println(arr[0]+"|"+arr[1]);
			jObject.put("dbName", arr[0]);
			jObject.put("dbType", arr[1]);
			jObject.put("dbPath", arr[2]);
			jsonArray.add(jObject);
		}
		jObj.put("data", jsonArray);
		jObj.put("code", 0);
		jObj.put("msg", "");
		jObj.put("count", 1000);
		return jObj;
	}

//	public static Object getDatabaseList1() {
//		String path = Config.RESULT_PATH+"dbCollect.csv";
//		JSONArray  jsonArray = new JSONArray();
//		JSONObject jObj = new JSONObject();
//		List<String> dbList = ReadFileUtil.readFile(path);
//		for (int i = 0; i < dbList.size(); i++) {
//			System.out.println(dbList.get(i));
//			String dbStr = dbList.get(i);
//			String arr[] = dbStr.split(",");
//			JSONObject jObject = new JSONObject();
//			jObject.put("dbName", arr[0]);
//			jObject.put("dbPath", arr[1]);
//			jsonArray.add(jObject);
//			
//		}
//		jObj.put("data", jsonArray);
//		return jObj;
//	}

	
	/**
	 * 获取图数据
	 * author：mark   
	 * @return
	 */
	@RequestMapping(value = "/getGraph")
	@ResponseBody
	public Object getGraph(@RequestParam(value = "graphName") String graphName) {

//		String shpath="/Users/mark/program/proWorkspace/pyCharmSrc/GenGraph/result/Execute_Command.sh";//.sh文件的绝对路径
//				String command = "sh /Users/mark/program/proWorkspace/pyCharmSrc/GenGraph/result/result_20191015112850/getSub2.sh /Users/mark/Documents/MasterLife/GraphDB/neo4j-community-3.4.6";
//		/Users/mark/program/proWorkspace/pyCharmSrc/GenGraph/result/result_2019101022310
		String path = getAvaliableDBPath();
		String command = "sh " + Config.RESULT_PATH+graphName+"/getSub.sh "+path;
//		String command = "sh /home/ubuntu/graph/GenGraph/result/result_2019111216205/getSub.sh /home/ubuntu/graph/neo4j-community-3.4.6";
		System.out.println(command);
		final List<String> processList = new ArrayList<String>(); 

		try {  
			final Process process = Runtime.getRuntime().exec(command);  	
			BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream(),"UTF-8"));  
			String line = "";  
			while ((line = input.readLine()) != null) {  
				processList.add(line); 
			}  
			input.close(); 

		} catch (IOException e) {  
			e.printStackTrace();  
		}  
		
		List<String> list = new ArrayList<>();
		for (String line : processList) {  
			
			if (line.length()>0) {
				if (line.charAt(0)=='|'&&line.charAt(2)=='\"'&&line.charAt(3)!='S'&&line.charAt(3)!='E') {
//					System.out.println(line);
//					JSONObject jobj1 = JSONObject.parseObject(arr[0]);
//					System.out.println(line);
					String arr[] = line.split("\"");
					String node1 = arr[1]+","+arr[3]+","+arr[5];
					System.out.println(node1);
					String node2 = arr[7]+","+arr[9]+","+arr[11];
					System.out.println(node2);
					String rel = arr[13]+","+arr[15]+","+arr[17];
					System.out.println(rel);
					String reString = node1+"&"+node2+"&"+rel;
					list.add(reString);
				}
			}
		}  
		return list;
		//		return ParseUtil.toObject("sss");
	}


	
	/**
	 * 获取图数据
	 * author：mark   
	 * @return
	 */
	@RequestMapping(value = "/getGraph_back")
	@ResponseBody
	public static Object getGraph_back(@RequestParam(value = "graphName") String graphName) {

//		String shpath="/Users/mark/program/proWorkspace/pyCharmSrc/GenGraph/result/Execute_Command.sh";//.sh文件的绝对路径
				String command = "sh /Users/mark/program/proWorkspace/pyCharmSrc/GenGraph/result/result_20191015112850/getSub2.sh /Users/mark/Documents/MasterLife/GraphDB/neo4j-community-3.4.6";
//		/Users/mark/program/proWorkspace/pyCharmSrc/GenGraph/result/result_2019101022310
//		String path = getAvaliableDBPath();
//		String command = "sh " + Config.RESULT_PATH+graphName+"/getSub.sh "+path;
//		String command = "sh /home/ubuntu/graph/GenGraph/result/result_2019111216205/getSub.sh /home/ubuntu/graph/neo4j-community-3.4.6";
		System.out.println(command);
		final List<String> processList = new ArrayList<String>(); 

		try {  
			final Process process = Runtime.getRuntime().exec(command);  	
//			BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));  
			BufferedReader input = new BufferedReader(new InputStreamReader(process.getErrorStream(), "UTF-8"));
			String line = "";  
			while ((line = input.readLine()) != null) {  
				processList.add(line); 
			}  
			input.close(); 

		} catch (IOException e) {  
			e.printStackTrace();  
		}  
		
		List<String> list = new ArrayList<>();
		for (String line : processList) {  
			System.out.println(line);
			if (line.length()>0) {
				if (line.charAt(0)=='\"'&&line.charAt(1)!='S'&&line.charAt(1)!='E') {
//					JSONObject jobj1 = JSONObject.parseObject(arr[0]);
//					System.out.println(line);
					String arr[] = line.split("\"");
					String node1 = arr[1]+","+arr[3]+","+arr[5];
					System.out.println(node1);
					String node2 = arr[7]+","+arr[9]+","+arr[11];
					System.out.println(node2);
					String rel = arr[13]+","+arr[15]+","+arr[17];
					System.out.println(rel);
					String reString = node1+"&"+node2+"&"+rel;
					list.add(reString);
				}
			}
		}  
		return list;
		//		return ParseUtil.toObject("sss");
	}


	public static void main(String[] args) {
//		getGraph();
		//		addDatabase();///////////////////////////
		//		getDatabase2();
//		getDatabaseList1();
//		System.out.println((3.67*3+3.67*3+3.67*1+4*3+3.67*3+4*4+4*4+3.67*3+3.67*3+4*3+3.67*2+2.67*3)/35);
//		testPerformanceOracle();
//		getGraph("");
	}


}
